package com.wasu.service;

import java.util.List;
import java.util.Random;

import org.apache.log4j.Logger;
import org.joda.time.DateTime;
import org.joda.time.Days;
import org.joda.time.LocalDate;
import org.joda.time.LocalTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.wasu.bean.AdSchedule;

@Controller
@RequestMapping("/redis")

public class RedisManager{
	private Logger log  = Logger.getLogger(RedisManager.class);

	@ResponseBody
	@RequestMapping("/init")
	public String init(){
		System.out.println("init");
		return "redirect:/redismanage.jsp";
	}
	
	@ResponseBody
	@RequestMapping("/clear")
	public int clear(@RequestParam("date") String date){
		DateTime now = DateTime.now();
		DateTimeFormatter df = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss");
		DateTime del = df.parseDateTime(date+" 00:00:00");
		if(Days.daysBetween(del, now).getDays()>0){
			String endwith="_done";
			return OrderJedis.delData(date,endwith);
		}
		return 0;
	}
	
	@ResponseBody
	@RequestMapping("/restart")
	public boolean restart(@RequestParam(value="adcode",required=true) String adcode,@RequestParam(value="starttime",required=true) String starttime){
		String datetmp = new LocalDate().toString();
		AdSchedule  schedule = null;
		if(OrderJedis.existsKey(adcode+"_"+datetmp)){
			schedule=OrderJedis.readSchedules(adcode+"_"+datetmp);
		}else{
			if(OrderJedis.existsKey(adcode+"_"+datetmp+"_done")){
				schedule= OrderJedis.readSchedules(adcode+"_"+datetmp+"_done");
				OrderJedis.del(adcode+"_"+datetmp+"_done");
			}
		}
		if(schedule!=null){
			schedule.setStarttime(starttime);
			boolean flag= OrderJedis.writeSchedule(adcode+"_"+datetmp, schedule);
			return flag;
		}
		return false;
	}
	
	@ResponseBody
	@RequestMapping("/restartAll")
	public int restartAll(){
		List<AdSchedule> list = OrderJedis.queryRunSchedules();
		LocalDate now = new LocalDate();
		for(AdSchedule schedule :list){
			LocalTime time = new LocalTime();
			LocalTime tmp = time.plusMinutes(new Random().nextInt(10));
			schedule.setStarttime(tmp.toString("HH:mm:ss"));
			log.info(schedule.getAdcode()+"_"+now.toString()+"---------"+tmp.toString("HH:mm:ss"));
			OrderJedis.writeSchedule(schedule.getAdcode()+"_"+now.toString(), schedule);
		}
		return list.size();
	}
}
